﻿Imports System.Net
Imports SysPadDB.Data

Public Class frmMain
    Dim vi As VersionInfo
    Public savePath As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\Syspad\"
    Private WithEvents Client As New WebClient
    Private Progress As DownloadProgressChangedEventArgs

    Private Sub UpdateInformation()
        Try
            If vi.user_version = vi.db_version Then
                lblCurrentVersion.Text = "You have SysPad " & vi.user_version & ", which is the latest version."
            Else
                lblCurrentVersion.Text = "Your version: " & vi.user_version

                lblUpdateVersion.Text = "Version: " & vi.db_version
                lblUpdateSize.Text = "Size: " & vi.size
                lblUpdateReleased.Text = "Released: " & vi.launch

                txtUpdateNotes.Clear()
                txtUpdateNotes.AppendText(vi.notes)
                btnCheck.Enabled = False
                btnUpdate.Enabled = True
            End If
        Catch ex As Exception
            MessageBox.Show("Could not retrieve update information." & vbNewLine & "Please try again later.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        btnCancel.Enabled = True
        btnUpdate.Enabled = False
        Try
            Dim repository As String = "http://www.serysoft.com/updates/syspad/" & vi.db_version & "/syspad_setup.exe"
            Dim destination As String = savePath & "syspad_setup.exe"
            Dim getFrom As New Uri(repository)

            ProgressBar1.Value = 0

            Client.DownloadFileAsync(getFrom, destination)
        Catch ex As Exception
            MessageBox.Show("Could not download new version." & vbNewLine & "Please try again later.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub Client_DownloadFileCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs) Handles Client.DownloadFileCompleted
        If ProgressBar1.Value = ProgressBar1.Maximum Then
            Dim ProcessList As Process() = Process.GetProcesses()
            For Each p In ProcessList
                If p.ProcessName = "SysPad" Then
                    p.Kill()
                End If
            Next

            Try
                Process.Start(savePath & "syspad_setup.exe")
            Catch ex As Exception
                MessageBox.Show("Error while launching installer.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try

            Try
                Dim wc As New WebClient
                wc.DownloadData("http://www.serysoft.com/webservice/sp_download.php")
                wc.Dispose()
            Catch ex As Exception

            End Try

            Me.Close()
        End If
    End Sub

    Private Sub Client_DownloadProgressChanged(ByVal sender As Object, ByVal e As System.Net.DownloadProgressChangedEventArgs) Handles Client.DownloadProgressChanged
        Dim BytesToReceive As Long = e.TotalBytesToReceive
        Dim BytesReceived As Long = e.BytesReceived

        ProgressBar1.Maximum = BytesToReceive
        ProgressBar1.Value = BytesReceived

        lblCompleted.Text = e.ProgressPercentage & "% done (" & FormatFileSize(e.BytesReceived) & " received out of " & If(e.TotalBytesToReceive = -1, "unknown", FormatFileSize(e.TotalBytesToReceive)) & ")"
    End Sub

    Private Function FormatFileSize(ByVal FileBytes As Long, Optional ByVal DecimalDigits As Integer = 1) As String
        Dim Power As Integer = Math.Floor(Math.Log(FileBytes, 1024))

        Return Format(FileBytes / (1024 ^ Power), "#." & StrDup(Math.Max(DecimalDigits, 0), "0")) & " " & New String() {"bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}(Power)
    End Function

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Client.CancelAsync()
        btnUpdate.Enabled = True
        Client.Dispose()
    End Sub

    Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
        If IsConnectionAvailable() Then
            UpdateInformation()
        Else
            MessageBox.Show("Could not connect to update server." & vbNewLine & "Please try again later.", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        vi = GetVersionInformation()

        lblCurrentVersion.Text = "Your version: " & vi.user_version
    End Sub
End Class
